<template>
  <div class="v-editor-diagramMap-relationCriterion g-jc-sb g-pd-l-8">
    <div class="g-one-line content">
      {{ valueData }}
    </div>
    <div
      v-if="selected && !row.readonly && !isModelDisabled"
      class="g-pd-r-4 img-btn"
    >
      <img
        src="statics/icons/app/iconmore.png"
        class="g-pointer"
        @click="handleClick"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { PropertyRow } from "../../types";
import { Ref, computed, inject } from "vue";
import { PropertyKey, RelationCriteriaType } from "@/constants/Enums";
import { relationCriteriaWindow } from "@/modules/model/modals/relationCriteria";
import { parseRC2Form } from "@/util/relationCriteria";
import { MetaclassType } from "@/constants/MetaclassType";
import { modelService } from "@/modules/model/service";
import { ModelData } from "@/constants/types";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

/**
 * 显示关系选择
 */
const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
}>();

const valueData = computed(() => {
  if (!props.row.value) return "";
  return parseRC2Form(props.row.value as string);
});

const handleClick = async () => {
  const data = await modelService.getModelDataForTabs(app.activeProject!.id, props.row.modelId);

  const isExpression = data.model.sts.includes("Customization::DerivedPropertySpecification");
  let validType: string = MetaclassType.Property;
  if (isExpression) {
    const parentProperties = await modelService.getModelProperties(app.activeProject!.id, data.model.ownerId);
    const metaConfigTarget = parentProperties.find(item => item.key == PropertyKey.MetaConfig_target);
    if (metaConfigTarget) {
      const targetValues = metaConfigTarget.value as ModelData[];
      if (targetValues && targetValues.length > 0) {
        validType = targetValues.map(item => item.id).join(",");
      }
    }
  }
  await relationCriteriaWindow
    .popup({
      projectId: app.activeProject!.id,
      attrTip: "expressionType",
      title: "表达式",
      modelId: props.row.modelId,
      type: RelationCriteriaType.DERIVED_PROPERTY_EXPRESSION,
      validType
    })
    .then(async res => {
      if (!res.success) return;
      // app.$bus.emit(BusEvent.REFRESH_PROPERTY, props.row.modelId, props.row.key);
    });
};
</script>
<style lang="scss">
@import "@/assets/css/theme.scss";
.v-editor-diagramMap-relationCriterion {
  height: 100%;
  .content {
    text-overflow: ellipsis;
    white-space: nowrap;
    display: flex;
    align-items: center;
    > span {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  > .img-btn {
    display: flex;
    align-items: center;
  }
}
</style>
